package com.idp.web.service.impl;

import com.idp.common.base.BusinessException;
import com.idp.common.constants.CommonConstants;
import com.idp.common.persistence.Page;
import com.idp.web.dao.DepartmentDao;
import com.idp.web.dto.DepartmentListDTO;
import com.idp.web.dto.DepartmentSelectListDTO;
import com.idp.web.dto.DepartmentTreeDTO;
import com.idp.web.entity.Department;
import com.idp.web.entity.HospitalDepartment;
import com.idp.web.service.IDepartmentService;
import com.idp.web.service.IHospitalDepartmentService;
import com.idp.web.vo.DepartmentSearchVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 医院科室service实现类
 *
 * @author xubinren
 * @version 1.0
 * @date 2018/2/28
 */
@Service("departmentService")
public class DepartmentServiceImpl implements IDepartmentService {

    @Resource
    private DepartmentDao departmentDao;

    @Resource
    private IHospitalDepartmentService hospitalDepartmentService;

    /**
     * 根据条件分页查询科室列表
     *
     * @param department 查询条件
     * @param page       页面信息
     * @return Page<Department>
     */
    @Override
    public Page<Department> findByPage(Department department, Page<Department> page) {
        page.setResult(departmentDao.find(department, page));
        return page;
    }

    /**
     * 根据条件查询科室列表
     *
     * @param department 查询条件
     * @return List<Department>
     */
    @Override
    public List<Department> findBySearch(Department department) {
        return departmentDao.find(department);
    }

    /**
     * 根据权重查询科室列表,参数只要不传1和2表示查询1（一级科室）
     *
     * @param weight 权重
     * @param hospitalId 医院id
     * @return List<DepartmentSelectListDTO>
     */
    @Override
    public List<DepartmentSelectListDTO> selectListByWeight(int weight, String hospitalId){
        if (CommonConstants.DEPARTMENT_WEIGHT_ONE == weight || CommonConstants.DEPARTMENT_WEIGHT_TWO == weight){
            return departmentDao.selectListByWeight(weight,hospitalId);
        }else {
            return departmentDao.selectListByWeight(CommonConstants.DEPARTMENT_WEIGHT_ONE,hospitalId);
        }
    }

    /**
     * 根据id查询对应的科室信息
     *
     * @param id 科室id
     * @return Department
     */
    @Override
    public Department getById(String id) {
        return departmentDao.getById(id);
    }

    /**
     * 新增
     *
     * @param department 科室信息
     * @param userId     用户id
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public boolean add(Department department, HospitalDepartment hospitalDepartment, String userId) {
        //验证是否已经存在相同的科室：根据科室名称
        if (checkByName(department.getDepartmentName())){
            return false;
        }
        department.preInsert(userId);

        //父id
        String parentId = department.getParentId();
        //根据父id设置权重
        if (StringUtils.isEmpty(parentId)){
            department.setParentId(CommonConstants.STRING_ZERO);
            department.setWeights(CommonConstants.INT_ONE);
        }else {
            Department department1 = getById(parentId.trim());
            department.setWeights(department1.getWeights() + CommonConstants.INT_ONE);
        }

        //排序字段
        Integer sort = department.getSort();
        if (null == sort){
            department.setSort(getDefaultSort(department.getParentId().trim()));
        }

        Integer changeNum = departmentDao.add(department);
        if (null == changeNum || CommonConstants.INT_ONE != changeNum) {
            return false;
        }

        //新建医院科室关系信息
        if(null != hospitalDepartment && !CommonConstants.ADMIN_ID.equals(userId)){
            hospitalDepartment.setDepartmentId(department.getId());
            hospitalDepartment.setHospitalId(userId);
            hospitalDepartmentService.add(hospitalDepartment,userId);
            return true;
        }else {
            return true;
        }

     }

    /**
     * 修改
     *
     * @param department 科室信息
     * @param userId     用户id
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public boolean update(Department department, String userId) {

        //原科室信息
        Department oldDepartment = getById(department.getId().trim());

        //验证是否已经存在相同的科室：根据科室名称
        if (checkByName(department.getDepartmentName())
                && !department.getDepartmentName().trim().equals(oldDepartment.getDepartmentName().trim())){
            return false;
        }

        //父id
        String parentId = department.getParentId();
        //根据父id设置权重
        if (StringUtils.isEmpty(parentId) || CommonConstants.DEPARTMENT_ROOT_ID.equals(parentId.trim())){
            department.setParentId(CommonConstants.STRING_ZERO);
            department.setWeights(CommonConstants.INT_ONE);
        }else {
            Department department1 = getById(parentId.trim());
            department.setWeights(department1.getWeights() + CommonConstants.INT_ONE);
        }

        //排序字段
        Integer sort = department.getSort();
        if (null == sort){
            department.setSort(getDefaultSort(department.getParentId().trim()));
        }

        department.preUpdate(userId);
        department.setCreateUser(oldDepartment.getCreateUser());
        department.setCreateDate(oldDepartment.getCreateDate());
        department.setLogicDelete(oldDepartment.getLogicDelete());
        Integer changeNum = departmentDao.update(department);
        if (null != changeNum && CommonConstants.INT_ONE == changeNum) {
            return true;
        }
        return false;
    }

    /**
     * 根据主键删除对应的科室信息
     *
     * @param id 科室id
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public void delete(String id) {
        departmentDao.delete(id);
    }

    /**
     * 根据父id查询对应的科室列表信息
     *
     * @param departmentSearchVo 查询条件
     * @return List<DepartmentListDTO>
     */
    @Override
    public List<DepartmentListDTO> findForTreeTable(DepartmentSearchVo departmentSearchVo) {
        if (null != departmentSearchVo && StringUtils.isEmpty(departmentSearchVo.getHospitalId())){
            return departmentDao.findForTreeTable(departmentSearchVo.getParentId());
        }else if (CommonConstants.ADMIN_PARENT_ID.equals(departmentSearchVo.getParentId())
                && CommonConstants.ADMIN_ID.equals(departmentSearchVo.getHospitalId())){
            return departmentDao.findForTreeTable(departmentSearchVo.getParentId());
        }else if (StringUtils.isNotEmpty(departmentSearchVo.getHospitalId())){
            return departmentDao.findTreeTableForHospital(departmentSearchVo);
        }
        return null;
    }

    /**
     * 科室树获取
     *
     * @return List<Department>
     */
    @Override
    public List<DepartmentTreeDTO> find(DepartmentSearchVo department){
        return departmentDao.selectAll(department);
    }

    /**
     * 根据科室名称验证是否已经存在相同的科室
     * 存在：返回true；不存在：返回false
     * 参数传递前请自己验证，此方法不会进行验证
     *
     * @param departmentName 科室名称
     * @return boolean
     */
    @Override
    public boolean checkByName(String departmentName){
        Department department = departmentDao.getByName(departmentName.trim());
        if (null == department){
            return false;
        }
        return true;
    }

    /**
     * 查询科室的统计信息
     *
     * @param type 科室权重：1，一级科室；2，二级科室
     * @param hospitalId 医院id
     * @return boolean
     */
    @Override
    public int queryStatistics(int type, String hospitalId){
        int queryNum = 0;
        Integer selectNum = departmentDao.queryStatistics(type,hospitalId);
        if (null == selectNum || selectNum < CommonConstants.INT_ZERO){
            queryNum = CommonConstants.INT_ZERO;
        }else{
            queryNum = selectNum;
        }
        return queryNum;
    }

    /**
     * 查询父id下的科室排序最大值，并加一
     * 用于用户在创建或编辑科室信息，排序没有填写的时候使用
     *
     * @param parentId 父id
     * @return boolean
     */
    @Override
    public int getDefaultSort(String parentId){
        if (StringUtils.isEmpty(parentId)){
            return CommonConstants.INT_ZERO;
        }
        int defaultSort = CommonConstants.INT_ZERO;
        Integer maxSort = departmentDao.getDefaultSort(parentId.trim());
        if (null == maxSort || maxSort < CommonConstants.INT_ONE){
            defaultSort = CommonConstants.INT_ONE;
        }else {
            defaultSort = maxSort + CommonConstants.INT_ONE;
        }
        return defaultSort;
    }

}